#!/usr/bin/env python
# -*- coding: utf-8 -*- 
#############################################################################
# GMangas
# Copyright (C) 2008  Ferraro Luciano (aka Lux) <luciano.ferraro@gmail.com>
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
############################################################################

import os
import sys
import thread
import time

import pygtk
pygtk.require("2.0")
import gtk

sys_stderr = sys.stderr

class Dialog (gtk.MessageDialog):
    def __init__(self, text, type="INFO"):
        rep_text = _("\nPlease report this bug here:\n http://code.google.com/p/gmangas/issues/entry")
        types = {"INFO":gtk.MESSAGE_INFO, "WARNING":gtk.MESSAGE_WARNING, 
        "QUESTION":gtk.MESSAGE_QUESTION, "ERROR":gtk.MESSAGE_ERROR}
        gtk.MessageDialog.__init__(self, type=types[type], 
                                   buttons=gtk.BUTTONS_OK, message_format=rep_text)
        self.format_secondary_text(text)

        self.set_position(gtk.WIN_POS_MOUSE)
        self.show_all()
        dialog_destroy = self.destroy
        destroy = lambda *x: dialog_destroy()
        self.connect('close', destroy)
        self.connect('response', destroy)

class GtkErrStream:
    def __init__(self, secondary_stream):
        self.secondary_stream = secondary_stream
        self.time = None
        self.buffer = None

    def handler(self):
        while time.time()-self.time < 1:
            time.sleep(0.3)
        thread.start_new_thread(Dialog, (self.buffer, "ERROR"))
        self.buffer = None

    def write(self, text):
        self.secondary_stream.write(text)        

        self.time = time.time()
        if self.buffer == None:
            self.buffer = ''
            thread.start_new_thread(self.handler, ())
        self.buffer += text

class Main:
    def stop(self, *x):
        sys.stderr = sys_stderr

    def start(self):
        stderr = GtkErrStream(sys.stdout)
        sys.stderr = stderr
